<?php

namespace app\common\util;

use app\common\exception\CatchException;

class ZipUtil
{
    /**
     * 生成压缩文件
     * @param $data
     * @param $prefix
     * @return \stdClass
     * @throws CatchException
     */
    public static function createZip($data = [], $prefix = 'default')
    {
        $date = date('Ymd');
        $dir = public_path("zip/" . $prefix ."/" . $date);
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
            chmod($dir, 0777);
        }

        $zip_name =  $prefix . '_' . date('YmdHis') . '.zip';
        $zip_path = $dir . $zip_name;
        $zip_path = str_replace("\\", "/", $zip_path);

        $zip = new \ZipArchive();
        $zip_res = $zip->open($zip_path, \ZipArchive::CREATE);
        if (!$zip_res) {
            throw new CatchException('生成zip失败', 500);
        }

        foreach ($data as $item) {
            if (!file_exists($item['path'])) {
                throw new CatchException('文件不存在：' . $item['path'], 404);
            }
            $zip->addFile($item['path'], $item['name']);
        }

        $zip->close();

        $zip_url = request()->domain() . getVirRootDir() . "/zip/" . $prefix . "/" . $date . "/" . $zip_name;

        $res = new \stdClass();
        $res->file_name = $zip_name;
        $res->path = $zip_path;//本地路径
        $res->url = $zip_url;//访问路径
        return $res;
    }
}
